<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title">我的频道</div>
      <div>
        <van-button type="danger" plain hairline round size="mini"
          @click="isEditChannel = !isEditChannel">{{isEditChannel?'完成':'编辑'}}
        </van-button>
      </div>
    </van-cell>
    <van-grid class='my-grid' :gutter="10">
      <van-grid-item class="grid-item" v-for="obj,index in channels"
        @click="changeChannel(index,obj)" :key="index">
        <van-icon name="clear" slot="icon"
          v-show="isEditChannel&&!fixedChannels.includes(obj.id)" />
        <span slot="text" class="text" :class="{active:index === active}">
          {{obj.name}}</span>
      </van-grid-item>
    </van-grid>
    <van-cell :border="false">
      <div slot="title">频道推荐</div>
    </van-cell>
    <van-grid class='recommend-grid' :gutter="10">
      <van-grid-item class="grid-item" icon="plus"
        v-for="channel in recommendChannels" :key="channel.id"
        @click="addChannel(channel)" :text="channel.name" />
    </van-grid>
  </div>
</template>

<script>
// 按需引入获取全部频道的Api
import {
  getAllChannelsApi,
  addUserChannelsApi,
  delUserChannelsApi
} from '@/api'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  // 组件名称
  name: 'ChannelEdit',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {
    channels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  // 组件状态值
  data () {
    return {
      allChannels: [],
      isEditChannel: false,
      fixedChannels: [0]
    }
  },
  // 计算属性
  computed: {
    // recommendChannels () {
    //   const reChannels = []
    //   this.allChannels.forEach(channel => {
    //     const ret = this.channels.find(myChannel => {
    //       return myChannel.id === channel.id
    //     })
    //     if (!ret) {
    //       reChannels.push(channel)
    //     }
    //   })
    //   return reChannels
    // }
    recommendChannels () {
      return this.allChannels.filter(channel => !this.channels.find(myChannel => channel.id === myChannel.id)
      )
    },
    ...mapState(['user'])
  },
  // 侦听器
  watch: {},
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
* 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
*/
  created () {
    this.loadAllChannels()
  },
  /**
* el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
* 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
*/
  mounted () { },
  // 组件方法
  methods: {
    async loadAllChannels () {
      try {
        const { data } = await getAllChannelsApi()
        // console.log(data)
        this.allChannels = data.data.channels
      } catch (err) {
        // console.log(err)
        this.$toast('获取全部频道失败')
      }
    },
    async addChannel (channel) {
      this.channels.push(channel)
      if (this.user) {
        try {
          await addUserChannelsApi({
            id: channel.id,
            seq: this.channels.length
          })
          this.$toast('添加成功')
        } catch (err) {
          this.$toast('添加失败，请稍后再试')
        }
      } else {
        setItem('TOUTIAO_CHANNELS', this.channels)
      }
    },
    changeChannel (index, channel) {
      if (this.isEditChannel) {
        // 如果是固定频道则不能删除
        if (this.fixedChannels.includes(channel.id)) {
          return
        }
        if (index <= this.active) {
          this.$emit('toggleChannel', this.active - 1)
        }
        this.channels.splice(index, 1)
        // console.log(index)
        this.delChannel(channel)
      } else {
        // console.log(1)
        // console.log(index)
        this.$emit('toggleChannel', index, false)
      }
    },
    async delChannel (channel) {
      if (this.user) {
        try {
          await delUserChannelsApi(channel.id)
        } catch (err) {
          this.$toast('删除失败')
        }
      } else {
        setItem('TOUTIAO_CHANNELS', this.channels)
      }
    }
  }
}
</script>

<style scoped lang="less">
.channel-edit {
  padding: 85px 0;

  .title-text {
    font-size: 32px;
    color: #333333;
  }
  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }
  /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
    }
  }

  /deep/ .recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }
  /deep/ .van-grid-item__icon-wrapper {
    position: unset;
  }
}
</style>
